package com.code.utils;

import com.code.Attribute;
import com.code.TableAttribute;
import com.code.enums.CodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.apache.log4j.Logger;

import java.io.*;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * FileName: GenerateUtils
 * Author:   wdq
 * Date:     2020/8/10 22:46
 * Description: 生成ftl文件工具类
 */
public class GenerateUtils {

    private static Logger logger = Logger.getLogger(GenerateUtils.class);

    public static Map<String, String> initDataType() {
        Map<String, String> map = new HashMap<>();
        map.put("NUMBER", "Long");
        map.put("VARCHAR2", "String");
        return map;
    }

    /**
     * 根据模板文件导出类File
     *
     * @param ftlName  模板文件名
     * @param codePath 生成代码路径
     * @throws IOException
     * @throws TemplateException
     */
    public static void exportFile(String ftlName, String codePath) throws IOException, TemplateException {

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDirectoryForTemplateLoading(new File(CodeEnum.TEMPLATE_FILE_PATH.getValue()));
        cfg.setDefaultEncoding(CodeEnum.FTLE_ENCODING.getValue());
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        Template temp = cfg.getTemplate(ftlName);
        // Create the root hash
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("packageName", "com.ricky.java");//包名
        root.put("className", "Person");//类名
        root.put("author", "wdq");//作者
        List<Attribute> attributeList = new ArrayList<Attribute>();
        attributeList.add(new Attribute("id", "Long"));
        attributeList.add(new Attribute("name", "String"));
        attributeList.add(new Attribute("age", "Integer"));
        attributeList.add(new Attribute("hobby", "List<String>"));

        root.put("attrs", attributeList);
        File dir = new File(codePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        OutputStream fos = new FileOutputStream(new File(dir, "Person.java")); //java文件的生成目录
        Writer out = new OutputStreamWriter(fos);
        temp.process(root, out);

        fos.flush();
        fos.close();

    }

    /**
     * 根据模板文件导出类File
     *
     * @param ftlName  模板文件名
     * @param codePath 生成代码路径
     * @throws IOException
     * @throws TemplateException
     */
    public static void exportFile(String ftlName, String codePath, String tableName) throws IOException, TemplateException {

        //读取模板文件
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
        cfg.setDirectoryForTemplateLoading(new File(CodeEnum.TEMPLATE_FILE_PATH.getValue()));
        cfg.setDefaultEncoding(CodeEnum.FTLE_ENCODING.getValue());
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        Template temp = cfg.getTemplate(ftlName);
        // Create the root hash
        //获取数据库配置信息
        PropertiesUtils propertiesUtils = PropertiesUtils.getInstance();
        String driver = propertiesUtils.getProperty(CodeEnum.DEFAULT_ORACLE_CLASS.getValue());
        String url = propertiesUtils.getProperty(CodeEnum.DEFAULT_ORACLE_URL.getValue());
        String username = propertiesUtils.getProperty(CodeEnum.DEFAULT_ORACLE_USERNAME.getValue());
        String pwd = propertiesUtils.getProperty(CodeEnum.DEFAULT_ORACLE_PWD.getValue());
        //获取数据
        Connection conn = DbUtils.getDbConnection(driver, url, username, pwd);
        List<TableAttribute> tableAttributeList = DbUtils.queryTableStructure(conn, tableName);
        Map<String, String> dataTypeMap = GenerateUtils.initDataType();
        String className = CodeUtils.formatterAttribute(tableName, true, true);
        Map<String, Object> root = new HashMap<>();
        root.put("packageName", "com.ricky.java");//包名
        root.put("className", className);//类名
        root.put("author", "wdq");//作者
        List<Attribute> attributeList = new ArrayList<>();
        tableAttributeList.forEach(tableAttribute -> {
            String name = CodeUtils.formatterAttribute(tableAttribute.getColumnName(), false, false);
            String type = dataTypeMap.get(tableAttribute.getDataType());
            attributeList.add(new Attribute(name, type));
        });
        root.put("attrs", attributeList);
        File dir = new File(codePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        OutputStream fos = new FileOutputStream(new File(dir, "Person.java")); //java文件的生成目录
        Writer out = new OutputStreamWriter(fos);
        temp.process(root, out);

        fos.flush();
        fos.close();

    }
}
